package com.android.showRoomApp;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

import com.android.showRoomApp.adapter.MainActivityListViewAdapter;
import com.android.showRoomApp.entity.ScreenMaterial;
import com.android.showRoomApp.util.SocketUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 首页
 */
public class MainActivity extends AppCompatActivity {


    //界面元素声明
    private ListView listView;
    private MainActivityListViewAdapter adapter;

    //内部变量声明
    private SharedPreferences sharedPreferences;
    private String no;
    private String password;
    private List<List<ScreenMaterial>> data = new ArrayList<>();


    //定时任务
    private Timer timer = new Timer();
    private TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //设置左上角appLOGO
        getSupportActionBar().setIcon(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);

        // 开启定时任务
        task = new TimerTask() {
            @Override
            public void run() {
                Log.i("zjq","正在执行定时任务");
                Log.i("zjq",data.toString());
                // 监测各个屏幕是否在线
                for (int i = 0; i < data.size(); i++) {
                    final int finalI = i;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            final ScreenMaterial material = data.get(finalI).get(0);
                            Boolean result = SocketUtils.checkSocketConnect(material.getLocalIP(),material.getPort());
                            Log.i("zjq","连接结果"+result);
                            for (int j = 0; j < data.get(finalI).size(); j++) {
                                data.get(finalI).get(j).setConnect(result);
                            }
                        }
                    }
                    ).start();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Toast.makeText(MainActivity.this,"正在更新状态",Toast.LENGTH_SHORT).show();
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };
        timer.schedule(task,2000,60*1000);


        //请求权限
        List<String> permissons = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            permissons.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            permissons.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (permissons.size() != 0) {
            ActivityCompat.requestPermissions(MainActivity.this,permissons.toArray(new String[permissons.size()]),1);
        }

        //获取数据
        sharedPreferences = getSharedPreferences(getString(R.string.app_shareFile),MODE_PRIVATE);
        no = sharedPreferences.getString("no","");
        password = sharedPreferences.getString("password","");


        //获取界面元素
        listView = findViewById(R.id.mainAct_listView);

        adapter = new MainActivityListViewAdapter(this,data);
        listView.setAdapter(adapter);

        getAllMaterialByExhibition();
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        MenuItem menuItem = menu.getItem(0);
        menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                goToSettingAct();
                return false;
            }
        });
        MenuItem exitItem = menu.getItem(1);
        exitItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                //退出app
                finish();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 该方法用于获取登录展厅所有屏幕的所有素材
     */
    private void getAllMaterialByExhibition (){
        RequestBody body = new FormBody.Builder().add("no",no).add("password",password).build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getString(R.string.app_ip)+"rest/localServer/getAllMaterialByExhibition")
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //解析响应
                ResponseBody responseBody = response.body();
                String responseString = responseBody.string();
                JsonObject responseObject = new Gson().fromJson(responseString, JsonObject.class);
                if (responseObject.get("success").getAsBoolean()){
                    // 请求成功，获取数据
                    JsonArray listData = responseObject.getAsJsonObject("obj").getAsJsonArray("screenMaterialMapList").getAsJsonArray();
                    packData(listData);

                    // 保存数据
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("listData",new Gson().toJson(listData));
                    if (editor.commit()){
                        Log.i("zjq","保存成功");
                    }else {
                        Log.i("zjq","保存失败");
                    }

                    Log.i("zjq",listData.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    //请求失败,跳转到设置页面重新设置
                    goToSettingAct();
                }
                Log.i("zjq",responseObject.toString());
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("zjq",e.toString());
                //没有网络或者服务器出错
                String dataStr = sharedPreferences.getString("listData","");
                if (!dataStr.isEmpty()){
                    JsonArray listData = new Gson().fromJson(dataStr,JsonArray.class);
                    packData(listData);
                }
            }
        });
    }


    /**
     * 跳转设置页面
     */
    public void goToSettingAct(){
        Intent intent = new Intent(MainActivity.this,SettingActivity.class);
        startActivity(intent);
        finish();
    }


    /**
     * 组装数据到data
     * @param listData
     */
    public void packData(JsonArray listData){
        //组装数据
        data.clear();
        Iterator<JsonElement> iterator = listData.iterator();
        while (iterator.hasNext()){
            JsonObject itemObject = iterator.next().getAsJsonObject();
            Set<String> keySet = itemObject.keySet();
            Iterator<String> keyIterator = keySet.iterator();
            List<ScreenMaterial> materialList = new ArrayList<>();
            while (keyIterator.hasNext()){
                String key = keyIterator.next();
                JsonArray value = itemObject.get(key).getAsJsonArray();
                Iterator<JsonElement> valueIterator = value.iterator();
                while (valueIterator.hasNext()){
                    JsonObject valueItem = valueIterator.next().getAsJsonObject();
                    ScreenMaterial screenMaterial = new Gson().fromJson(valueItem,ScreenMaterial.class);
                    materialList.add(screenMaterial);
                }
            }
            data.add(materialList);
        }
    }
}
